package common.classes;

import java.util.HashMap;
import java.util.Map;

public class SessionSupporter {
	int sid;
	long timeLimit;
	Map<Integer, Long> map;
	
	public SessionSupporter() {
		this.sid = 1;
		this.map = new HashMap<Integer, Long>();
		this.timeLimit = 120000;
	}
	
	public SessionSupporter(long timeLimit) {
		this();
		this.timeLimit = timeLimit;
	}
	
	private boolean tryToRemoveSomeSID() {
		boolean removed = false;
		long currentTime = System.currentTimeMillis();
		for (Map.Entry<Integer, Long> entry : map.entrySet()) {
			if ((currentTime - map.get(entry.getKey()).longValue()) > timeLimit) {
				this.map.remove(entry.getKey());
				removed = true;
			}
		}
		return removed;
	}
	
	public 	int add() {
		tryToRemoveSomeSID();
		if (this.map.size() == 500) return -1;
		if (this.sid == 1000) {
			this.sid = 1;
		}
		while (this.map.containsKey(this.sid)) this.sid++;
		this.map.put(this.sid, System.currentTimeMillis() + this.timeLimit);
		return this.sid;
	}
	
	public long getTimeFor(int id) {
		if (this.map.containsKey(id)) return this.map.get(id);
		return 0L;
	}
}
